<?php

namespace app\admin\controller\userbusiness;
use think\Db;

use app\common\controller\Backend;

/**
 * 商机
 *
 * @icon fa fa-circle-o
 */
class PublicBusiness extends Backend
{

    /**
     * PublicBusiness模型对象
     * @var \app\admin\model\userbusiness\PublicBusiness
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\userbusiness\PublicBusiness;
        $this->view->assign("pushswitchList", $this->model->getPushswitchList());
    }


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $balance = Db::name('admin')->find($this->auth->id)['point'];
            $this->assign('balance',$balance,0);
            return $this->view->fetch();
        }
        $action = $this->request->get('action');
        if($action =='getType'){
            return getTypes();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where('status','0')
            ->where(function ($query){ 
                $query->where('pushswitch','1')
                ->whereOr('id','IN',function ($query) {
                $query->name('push_users')->where('user_id', $this->auth->id)->field('business_id');
                });
            })
            ->order($sort, $order)
            ->paginate($limit);
        $typeList = Db::name('btype')->field('id,name')->select();
        foreach ($list as $k => $v) {
            foreach ($typeList as $vv) { 
                if($v['btype_id'] == $vv['id']){
                    $list[$k]['bname'] = $vv['name'];
                }
            }
        }
        foreach($list->items() as $k=>$v){
            $list->items()[$k]['mobile'] = $this->maskPhoneNumber($v['mobile']);
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    /**
     * 获取商机
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $params = $this->request->param('ids');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $result = false;
        Db::startTrans();
        try {
            //会员点数变动
            $uid = $this->auth->id;
            $business = Db::name('business')->find($params);
            $user = Db::name('admin')->find($uid);
            $point = $business['point'];
            $user_point = $user['point'];
            if($user_point < $point){
                $this->error('商机点不足');
            }
            $udata['point'] = $user_point - $point;
            $result = Db::name('admin')->where('id',$uid)->update($udata);
            if(!$result){
                $this->error(__('No rows were updated'));
            }
            //点数变动日志
            $log_data['user_id'] = $uid;
            $log_data['score'] = $point;
            $log_data['before'] = $user_point;
            $log_data['after'] = $udata['point'];
            $log_data['createtime'] =time();
            $log_data['memo'] = '用户:'.$user['username'].'领取项目:'.$business['b_name'].' 消耗点数';
            $result = Db::name('user_point_log')->insert($log_data);
            if(!$result){
                $this->error(__('No rows were updated'));
            }
            //项目添加领取人
            $data['owner_id'] = $uid;
            $data['status'] = 1;
            $result = Db::name('business')->where('id',$params)->update($data);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    //手机号打码
    function maskPhoneNumber($phoneNumber) {
        // 检查手机号是否有效，必须是11位数字
        if (preg_match('/^\d{11}$/', $phoneNumber)) {
            $prefix = substr($phoneNumber, 0, 3); 
            $maskedDigits = str_repeat('*', 8);
            $suffix = substr($phoneNumber, -8);
            $maskedPhoneNumber = $prefix . $maskedDigits ;
            return $maskedPhoneNumber;
        } else {
            // 不是有效的手机号
            return "Invalid phone number";
        }
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
